package chpt10.mvc.gui;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import chpt10.mvc.model.User;
import chpt10.mvc.model.UserAuthentication;

public class LoginFrame extends JFrame {
	private JTextField usernameField;
	private JPasswordField passwordField;
	private JButton loginButton;
	private UserAuthentication userAuth;

	public LoginFrame() {
		userAuth = new UserAuthentication();
		setTitle("Login");
		setSize(300, 150);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JPanel panel = new JPanel();
		add(panel);
		placeComponents(panel);
	}

	private void placeComponents(JPanel panel) {
		panel.setLayout(null);

		JLabel userLabel = new JLabel("User:");
		userLabel.setBounds(10, 20, 80, 25);
		panel.add(userLabel);

		usernameField = new JTextField(20);
		usernameField.setBounds(100, 20, 165, 25);
		panel.add(usernameField);

		JLabel passwordLabel = new JLabel("Password:");
		passwordLabel.setBounds(10, 50, 80, 25);
		panel.add(passwordLabel);

		passwordField = new JPasswordField(20);
		passwordField.setBounds(100, 50, 165, 25);
		panel.add(passwordField);

		loginButton = new JButton("Login");
		loginButton.setBounds(10, 80, 80, 25);
		panel.add(loginButton);
		loginButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// 1. 从view中获取数据
				String username = usernameField.getText();
				String password = new String(passwordField.getPassword());
				// 2. 调用model(UserAuthentication类)来处理数据
				User user = userAuth.authenticate(username, password);
				// 3. 根据model处理的结果更新view（这里只是显示了对话框）
				if (user != null) {
					JOptionPane.showMessageDialog(null, "登录成功");
				} else {
					JOptionPane.showMessageDialog(null, "用户名密码错误！");
				}
			}
		});
	}

	public static void main(String[] args) {
		EventQueue.invokeLater(() -> {
			LoginFrame f = new LoginFrame();
			f.setVisible(true);
			f.setLocationRelativeTo(null);
		});
		System.out.println("end");
	}
}